<!-- 生长发育 -->
<template>
  <!-- 筛选条件 -->
  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="企业名称" v-if="companySelect">
        <el-select filterable clearable v-model="formInline.companyId">
          <el-option v-for="item in companyNameList" :label="item.name" :value="item.id" :key="item.id" />
        </el-select>
    </el-form-item>
    <el-form-item label="选择牛号">
      <el-select clearable filterable v-model="formInline.cowId">
        <el-option v-for="item in allComNameList" :label="`${item.code}-${item.breed}-${item.genderName}`" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="品种">
      <el-select clearable filterable v-model="formInline.cowBreed">
        <el-option v-for="(item, index) in breedList" :key="index" :label="item.name" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="测定人">
      <el-select filterable clearable v-model="formInline.createUserId" placeholder="请选择测定人">
        <el-option v-for="item in userSelectList" :key="item.id" :label="item.username" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button icon="Search" @click="search">查询</el-button>
      <!-- <el-button type="success" icon="Upload">导入超声波测定记录</el-button> -->
      <!-- 测试 -->
      <!-- <el-upload class="uploadBox" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess" :headers="headers" action="/api/growth/upload">
        <el-button type="primary">测试-上传</el-button>
      </el-upload> -->
      <!-- <el-button type="success" @click="donwLoadFile">测试-下载</el-button> -->
      <!-- 测试end -->
    </el-form-item>
  </el-form>

  <div class="mb-4" style="margin-bottom: 18px;">
    <el-button v-if="uploadButton" type="primary" icon="Upload" @click="isImportDialog = true">导入生长发育记录</el-button>
    <el-button type="success" icon="Download">导出</el-button>
  </div>

  <!-- 表格 -->
  <el-table :data="tableData" stripe border style="width: 100%;">
    <el-table-column prop="cowCode" label="牛号" width="350" fixed="left">
      <template #default="scope">
        <div style="display: flex;">
          <span>{{ scope.row.cowCode }}</span>
          <!-- 性别 -->
          <el-tag v-if="scope.row.genderName == '公牛'" style="margin-left: auto;" effect="dark" type="primary" size="small">{{ scope.row.genderName }}</el-tag>
          <el-tag v-if="scope.row.genderName == '母牛'" style="margin-left: auto;" effect="dark" type="danger" size="small">{{ scope.row.genderName }}</el-tag>
          <!-- 品种 -->
          <el-tag style="margin: 0 5px;" effect="dark" type="success" size="small">{{ scope.row.breed }}</el-tag>
          <!-- 年龄 -->
          <el-tag effect="dark" type="info" size="small">{{ scope.row.age }}</el-tag>
        </div>
      </template>
    </el-table-column>
    <el-table-column v-if="companyColumn" prop="companyName" label="企业名称" width="150" show-overflow-tooltip />
    <el-table-column prop="weight" label="体重(kg)" width="120" />
    <el-table-column prop="height" label="体高(cm)" width="120" />
    <el-table-column prop="crossHeight" label="十字部高(cm)" width="120" />
    <el-table-column prop="bodyLength" label="体斜长(cm)" width="120">
      <template #default="scope">
        <div style="display: flex; align-items: center;">
          <span style="margin-right: 10px;">{{ scope.row.bodyLength }}</span>
          <el-tag v-if="scope.row.bodyLengthMeasuring == '软尺'" type="primary" size="small" effect="light" round>软尺</el-tag>
          <el-tag v-if="scope.row.bodyLengthMeasuring == '硬尺'" type="danger" size="small" effect="light" round>硬尺</el-tag>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="chestGirth" label="胸围(cm)" width="120" />
    <el-table-column prop="backFatThickness" label="背膘厚(mm)" width="120" />
    <el-table-column prop="eyeArea" label="眼肌面积(cm2)" width="130" />
    <el-table-column prop="createUserName" label="记录人" width="120" />
    <el-table-column prop="recordDate" label="记录日期" width="120" />
    <el-table-column label="操作" fixed="right" :width="tdWidthItem">
      <template #default="scope">
        <div ref="tdWidth" style="display: inline-block; white-space: normal;">
        <el-button icon="Tickets" size="small" @click="detailsItem(scope.row.id)">详情</el-button>
        <el-button v-if="editButton" type="primary" icon="Edit" size="small" @click="editItem(scope.row.id)">编辑</el-button>
        <el-button v-if="deleteButton" type="danger" icon="Delete" size="small" @click="deleteItem(scope.row.id)">删除</el-button>
        <el-button v-if="errorButton" type="info" icon="Warning" size="small" @click="abnormalHandler">数据异常</el-button>
        </div>
      </template>
    </el-table-column>
  </el-table>
  <br/>
  <!-- 分页器 -->
  <el-pagination
        v-model:currentPage="pageNo"
        v-model:page-size="limit"
        :page-sizes="[15, 30, 50, 100]"
        :small="false"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
        @current-change="getCowGrowthPage"
        @size-change="sizeChange"
    />

  <!-- 导入生长发育记录弹窗 -->
  <upload :isImportDialog="isImportDialog" @closeUploadDialog="closeUploadDialog"></upload>

  <!-- 编辑弹窗 -->
  <edit :isShowEdit="isShowEdit" :editId="editId" @closeEditDrawer="closeEditDrawer"></edit>

  <!-- 详情弹窗 -->
  <detail :isShowDetails="isShowDetails" :detailsId="detailsId" @closeDetailsDrawer="closeDetailsDrawer"></detail>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getItem } from '@/utils/storage.js'
import { reqDonwLoadFile, reqGetCowGrowthPage, reqCowGrowthDelete } from '@/api/daily'
import { reqGetCompanyNameList } from '@/api/company'
import { reqGetBreedList } from '@/api/cattleStructure'
import { reqGetUserSelectList } from '@/api/user'
import { reqCowGrowthCowSelect } from '@/api/publicCowSelect'
import upload from './upload/index.vue'
import edit from './edit/index.vue'
import detail from './details/index.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
// 引入用户相关小仓库
import useUserStore from '@/store/modules/user'
let userStore = useUserStore()
const companyColumn = userStore.componentConfig.companyColumn // 企业名称列-是否显示
const companySelect = userStore.componentConfig.companySelect // 企业下拉-是否显示
const addButton = userStore.componentConfig.addButton // 新增按钮-是否显示
const deleteButton = userStore.componentConfig.deleteButton // 删除按钮-是否显示
const editButton = userStore.componentConfig.editButton // 编辑按钮-是否显示
const errorButton = userStore.componentConfig.errorButton // 数据异常按钮-是否显示
const uploadButton = userStore.componentConfig.uploadButton // 导入按钮-是否显示

// 分页器当前页码
let pageNo = ref(1)
// 每一页展示多少条数据
let limit = ref(15)
// 数据总条数
let total = ref(0)

// 获取企业下拉列表数据
let companyNameList = ref([])
const getCompanyNameList = async () => {
  let res = await reqGetCompanyNameList()
  companyNameList.value = res.data
  // formInline.companyId = companyNameList.value[0].id
}

// 表单收集
const formInline = reactive({
  companyId: '', // 企业
  cowId: '', // 牛号
  createUserId: '', // 测定人id
  cowBreed: '', // 品种
  sortName: '', // 排序字段名称
  sortType: '', // 排序类型：ascending-正序、descending-倒序
})

// 点击查询按钮
const search = () => {
  pageNo.value = 1
  getCowGrowthPage()
}

// 导入生长发育记录弹窗
let isImportDialog = ref(false)

// 编辑弹窗
let isShowEdit = ref(false)

// 详情弹窗
let isShowDetails = ref(false)

// 关闭编辑弹窗
const closeEditDrawer = (val) => {
  isShowEdit.value = val
  getCowGrowthPage()
}

// 关闭详情弹窗
const closeDetailsDrawer = (val) => {
  isShowDetails.value = val
}

// 获取表格数据
const tableData = ref([])
const getCowGrowthPage = async () => {
  let res = await reqGetCowGrowthPage(Object.assign(formInline, {
    pageNumber: pageNo.value, // 页号
    pageSize: limit.value // 每页数量
  }))
  if(res.status == 200){
    total.value = res.data.totalRow
    tableData.value = res.data.records
  }
}

// 获取牛品种，筛选下拉列表
let breedList = ref([])
const getBreedList = async () => {
    let res = await reqGetBreedList()
    breedList.value = res.data
}

// 获取用户（测定人）下拉列表
let userSelectList = ref([])
const getUserSelectList = async () => {
    let res = await reqGetUserSelectList()
    userSelectList.value = res.data
}

// 分页的下拉菜单发生改变时触发
const sizeChange = () => {
  pageNo.value = 1
  getCowGrowthPage()
}

const headers = ref({ authorization: getItem('TOKEN')})

// 上传之前的钩子
const beforeAvatarUpload = (rawFile) => {
  console.log('rawFile', rawFile)
}

// 上传文件成功的钩子
const handleAvatarSuccess = (response) => {
  console.log('response', response)
}

// 点击下载
const donwLoadFile = async () => {
  let res = await reqDonwLoadFile()
  let url = URL.createObjectURL(res)
	let a = document.createElement("a")
	  a.style = "display: none"
		a.target = "_blank"
		// a.download = "file"
		a.href = url
		document.body.appendChild(a)
		a.click()
		document.body.removeChild(a)
		URL.revokeObjectURL(url)
}

// 关闭上传弹窗
const closeUploadDialog = (val) => {
  isImportDialog.value = val
  getCowGrowthPage()
}

// 获取牛号下拉列表
let allComNameList = ref([])
const cowGrowthCowSelect = async () => {
  let res = await reqCowGrowthCowSelect()
  allComNameList.value = res.data
}

// 点击详情
let detailsId = ref('')
const detailsItem = (id) => {
  detailsId.value = id
  isShowDetails.value = true
}

// 编辑某一行
let editId = ref('')
const editItem = (id) => {
  editId.value = id
  isShowEdit.value = true
}

// 删除某一行
const deleteItem = (id) => {
  ElMessageBox.confirm('请确认是否删除？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let res = await reqCowGrowthDelete({ id })
    if(res.status == 200){
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      getCowGrowthPage()
    }
  }).catch(() => {
    
  })
}

// 异常按钮
const abnormalHandler = () => {
  ElMessageBox.prompt('请输入异常原因', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    closeOnClickModal: false,
    inputPattern: /^.+$/,
    inputErrorMessage: '请填写异常原因'
  }).then((res) => {
    console.log('异常原因为：', res.value)
  }).catch(() => {
    console.log('取消填写异常原因')
  })
}

// 组件挂载完毕
onMounted(async () => {
  await getCompanyNameList() // 获取企业下拉列表
  await cowGrowthCowSelect() // 获取牛号下拉列表
  await getBreedList() // 获取品种下拉列表
  await getUserSelectList() // 获取测定人下拉列表
  await getCowGrowthPage() // 获取表格数据
  widthAuto()
})

// 设置操作栏按钮，宽度自适应
const tdWidthItem = ref(300)
const tdWidth = ref()
const widthAuto = () => {
    setTimeout(() => {
        tdWidthItem.value = tdWidth.value.offsetWidth + 30
    }, 500)
}
</script>

<style scoped lang="scss">
:deep(.uploadBox .el-upload-list){
  margin-bottom: 0;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>